/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.iasd.youthshelter.pathfinder.wizards.actions;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.util.NbBundle.Messages;
import pt.iasd.youthshelter.pathfinder.wizards.ChurchTablePanel;
import pt.iasd.youthshelter.datacore.controller.exceptions.IllegalOrphanException;
import pt.iasd.youthshelter.datacore.controller.exceptions.NonexistentEntityException;
import pt.iasd.youthshelter.datamodel.Church;
import pt.iasd.youthshelter.datamodel.service.ChurchController;

@ActionID(
        category = "Management",
        id = "pt.iasd.youthshelter.pathfinder.wizards.actions.ShowChurchPanelAction")
@ActionRegistration(
        iconBase = "pt/iasd/youthshelter/pathfinder/wizards/actions/icon.png",
        displayName = "#CTL_ShowChurchPanelAction")
@ActionReferences({
    @ActionReference(path = "Menu/Management", position = 100),
    @ActionReference(path = "Toolbars/Management", position = 100),
    @ActionReference(path = "Shortcuts", name = "D-T")
})
@Messages("CTL_ShowChurchPanelAction=Churches")
public final class ShowChurchPanelAction implements ActionListener {
    private static final ResourceBundle bundle = java.util.ResourceBundle.getBundle("pt/iasd/youthshelter/pathfinder/Bundle");
    /* Logging object. */
    private Logger logger = Logger.getLogger(this.getClass().getName());

    @Override
    public void actionPerformed(ActionEvent e) {
        ProgressHandle pHandle = ProgressHandleFactory.createHandle(
                    bundle.getString("ProgressBarWizard"));
        pHandle.start();
        final ChurchTablePanel churchPanel = new ChurchTablePanel();
        DialogDescriptor dialog = new DialogDescriptor(churchPanel, bundle.getString("Church.Panel"), true, new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                if(e.getSource() == DialogDescriptor.OK_OPTION) {
                    Set<Integer> edited = churchPanel.getEditedChurches();
                    Set<Integer> removed = churchPanel.getRemovedChurches();
                    ChurchController controller = Lookup.getDefault().lookup(ChurchController.class);
                    for(Church church : churchPanel.getChurches()) {
                        if(church.getId() == null) {
                            controller.create(church);
                        } else {
                            int churchId = church.getId();
                            if(removed.contains(churchId)) {
                                try {
                                    controller.destroy(churchId);
                                } catch (IllegalOrphanException ex) {
                                    Exceptions.printStackTrace(ex);
                                } catch (NonexistentEntityException ex) {
                                    logger.log(Level.INFO, String.format(
                                        bundle.getString("Church.Remove.Error")
                                                .replace("\n", System.getProperty("line.separator")), churchId));
                                }
                            } else if(edited.contains(churchId)) {
                                try {
                                    controller.edit(church);
                                } catch (NonexistentEntityException ex) {
                                    controller.create(church);
                                } catch (Exception ex) {
                                    logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
                                    NotifyDescriptor dialog = new NotifyDescriptor.Message(
                                        String.format(
                                            bundle.getString("Church.Save.Error")
                                                .replace("\n", System.getProperty("line.separator")),
                                            ex.getLocalizedMessage()),
                                        NotifyDescriptor.ERROR_MESSAGE);
                                    DialogDisplayer.getDefault().notify(dialog);
                                }
                            }
                        }
                    }
                }
            }
        });
        pHandle.finish();
        DialogDisplayer.getDefault().notify(dialog);
    }
}
